﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;
using NHibernate.Linq;
using Longtop.Web.WebSite.Models;
using Longtop.Web.SaleWeb.Models;
using Castle.ActiveRecord;
namespace Longtop.Web.WebSite.Filters {
    public class PermissionAuthorizeAttribute : AuthorizeAttribute {


        public ActionDescriptor ActionDescriptor { get; set; }
        public Admin.Controllers.ControllerBase Controller { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            // return base.AuthorizeCore(httpContext);
            if (httpContext == null) {
                throw new ArgumentNullException("httpContext");
            }
            object[] attrs = ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(IgnoreAuthorizeAttrobite), true);
            if (attrs.Length == 1)//是否应用了忽略验证特性
                return true;
            else {
                attrs = ActionDescriptor.GetCustomAttributes(typeof(IgnoreAuthorizeAttrobite), true);
                if (attrs.Length == 1)//是否应用了忽略验证特性
                    return true;
            }


            IPrincipal user = httpContext.User;
            if (user.IsInRole("system")) return true;
            if (!user.Identity.IsAuthenticated)
                return false;

            var controllerName = ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
            controllerName = controllerName.Substring(0, controllerName.Length - 10);
            var actionName = controllerName + "." + ActionDescriptor.ActionName;
            actionName = actionName.ToLower();
            var roles = System.Web.Security.Roles.GetRolesForUser();
            using (new SessionScope()) {
                return this.Controller.ARContext.Session.Linq<RolePermission>().Any(rp => rp.PermissionName == actionName && roles.Contains(rp.RoleName));
            }
        }


        public override void OnAuthorization(AuthorizationContext filterContext) {
            this.Controller = filterContext.Controller as Admin.Controllers.ControllerBase;
            this.ActionDescriptor = filterContext.ActionDescriptor;
            if (!AuthorizeCore(filterContext.HttpContext)) {
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                    filterContext.Result = new ViewResult() { ViewName = "nopermission" };
                else
                    filterContext.Result = new HttpUnauthorizedResult();
            }
        }

        protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) {

            return base.OnCacheAuthorization(httpContext);
        }

    }
}
